<template>
    <div id="table">
  
      <el-dialog title="设备详情" :visible.sync="dialogFormVisible"
      @open="handleDialogOpen"
      >
        
            <el-table
          :data="showData"
          style="width: 100%"
          height="250">
          <el-table-column
            prop="id"
            label="设备编号"
            width="100">
          </el-table-column>
          <el-table-column
            prop="hum"
            label="湿度"
            width="100">
          </el-table-column>
          <el-table-column
            prop="temp"
            label="温度">
          </el-table-column>
          <el-table-column
            prop="light"
            label="光照">
          </el-table-column>
          <el-table-column
            prop="uploadDate"
            label="日期">
          </el-table-column>
        </el-table>

        <div id = "main" style=" height: 350px;width:700px;margin-top: 20px;">

        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
        
        </div>
  
      </el-dialog>

      <el-dialog title="设备详情" :visible.sync="dialogFormVisibles">
        
        <el-descriptions title="设备信息">
          <el-descriptions-item label="查找失败">不存在此设备</el-descriptions-item>
        </el-descriptions>
  
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibles = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisibles = false">确 定</el-button>
        </div>
  
      </el-dialog>
  
      <el-autocomplete
        class="inline-input"
        id="search"
        v-model="state2"
        :fetch-suggestions="querySearch"
        placeholder="请输入内容"
        :trigger-on-focus="false"
        @change="handleSelect"
        @select="handleSelect"
      ></el-autocomplete>
     
      <el-table
        :data="pagination"
        style="width: 100%"
        v-if = "!state2"
        @row-click="update"
        >
        <el-table-column
          prop="id"
          label="编号"
          width="130"
          sortable
          column-key="id"
          >
        </el-table-column>
        <el-table-column
          prop="name"
          label="设备名称"
          width="130"
          sortable
          column-key="name"
          >
        </el-table-column>
        <el-table-column
          prop="address"
          label="设备地址"
          sortable
          width="250"
          >
        </el-table-column>
        <el-table-column
          prop="lat"
          sortable
          label="经度">
        </el-table-column>
        <el-table-column
          prop="lng"
          sortable
          label="纬度">
        </el-table-column>
        <el-table-column
          prop="dtuid"
          sortable
          label="dtu编号">
        </el-table-column>
        <el-table-column
        prop="state"
        sortable
        label="设备状态">

      </el-table-column>
      </el-table>
  
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="pageSizes" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
          v-if="!state2"
          >
        </el-pagination>
  
      <el-table
        v-else
        :data="pagination"
        style="width: 100%"
        @row-click="update">
        <el-table-column
          prop="id"
          label="编号"
          width="130"
          sortable
          column-key="id"
          >
        </el-table-column>
        <el-table-column
          prop="name"
          label="设备名称"
          width="130"
          sortable
          column-key="name"
          >
        </el-table-column>
        <el-table-column
          prop="address"
          label="设备地址"
          sortable
          width="250"
          >
        </el-table-column>
        <el-table-column
          prop="lat"
          sortable
          label="经度">
        </el-table-column>
        <el-table-column
          prop="lng"
          sortable
          label="纬度">
        </el-table-column>
        <el-table-column
          prop="dtuid"
          sortable
          label="dtu编号">
        </el-table-column>
        <el-table-column
        prop="state"
        sortable
        label="设备状态">

      </el-table-column>
      </el-table>
      <el-pagination @size-change="handleNewSizeChange" @current-change="handleNewCurrentChange" :current-page="currenNewPage"
          :page-sizes="pageNewSizes" :page-size="pageNewSize" layout="total, sizes, prev, pager, next, jumper"
          :total="totalNewItems"
          v-if="state2"
          >
        </el-pagination>
  
    </div>
    
  </template>
  
  <script>
import axios from 'axios'
import * as echarts from 'echarts';
  export default {
    data(){
      return{
        times:[],
        temps:[],
        hums:[],
        light:[],
        searchtable: [],
        pagination: [],
        currentPage: 1,
        // 分页的分界线
        start: 0,
        end: 10,
        pageSize: 6, // 每页显示的条目数量
        totalItems: 0, // 数据库中条目数量
        pageSizes: [6, 8, 10, 20] ,// 每页显示条目数量的选项
  
        currentNewPage: 1,
        // 分页的分界线
        Newstart: 0,
        Newend: 10,
        pageNewSizes: [6, 8, 10, 20],
        pageNewSize: 6,
        totalNewItems:0,
  
        restaurants: [],
        state2: '',
        id: 0,
        tableData: [],
          dialogFormVisible: false,
          dialogFormVisibles: false,
          deviceData:[
          ],
        showData:[]
      }
    },
    methods:{
      getEcharts()
      {
        var chartDom = document.getElementById('main');
        var myChart = echarts.init(chartDom);
        var option;
        option = {
          title: {
            text: '折线图'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['温度', '湿度','光照']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.times
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '温度',
              type: 'line',
              stack: 'Total',
              data: this.temps
            },
            {
              name: '湿度',
              type: 'line',
              stack: 'Total',
              data: this.hums
            },
            {
              name: '光照',
              type: 'line',
              stack: 'Total',
              data: this.light
            },
            
          ]
        };
        option && myChart.setOption(option);
      }
      ,
      add()
      {
        // 挂载设备
      },
      handleDialogOpen(){
        this.$nextTick(() => {
          this.getEcharts()
        })
      },
      async update(row)
      {
        let user = JSON.parse(localStorage.getItem("honey-user") || '{}')
        const config = {
            headers: {
                // 设置内容类型为JSON
                'Content-Type': 'application/json;charset=UTF-8',
                // 添加token到请求头
                'token': user.token || '',
            }
        }
          //this.$request.get('/deviceData/${row.id}').then(res => {
              const res = await axios.get(`http://127.0.0.1:8000/deviceData/${row.id}`,config)
              if (res.data.data) {
                  this.showData = res.data.data
                  this.dialogFormVisible = true
              } else {
                  this.dialogFormVisibles = true
              }
         // })
        this.times = this.showData.map(item => item.uploadDate)
        this.temps = this.showData.map(item => item.temp)
        this.hums = this.showData.map(item => item.hum)
        this.light = this.showData.map(item => item.light)
      },
      handleSelect()
      {
        this.searchtable = this.tableData.filter(item => {
              return String(item.id) === this.state2
          })
        if(this.state2 == '')
          this.searchtable = this.tableData
        this.searchpage()
      },
      filterHandler(value, row, column) {
          const property = column['property'];
          return row[property] === value;
        },
      querySearch(queryString, cb) {
          var restaurants = this.restaurants;
          var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
          // 调用 callback 返回建议列表的数据
          cb(results);
      },
      createFilter(queryString) {
          return (restaurant) => {
            return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
          };
      },
      loadAll() {
          return [
          ]
        },
      fetchData () {
        this.start = (this.currentPage - 1) * this.pageSize
        this.end = this.start + this.pageSize
        this.pagination = this.tableData.slice(this.start, this.end)
        this.totalItems = this.tableData.length;
        this.totalNewItems = this.tableData.length;
      },
      searchpage(){
        this.Newstart = (this.currentNewPage - 1) * this.pageNewSize
        this.Newend = this.Newstart + this.pageNewSize
        this.pagination = this.searchtable.slice(this.Newstart, this.Newend)
        this.totalNewItems = this.searchtable.length;
      },
      handleSizeChange (newSize) {
        this.pageSize = newSize
        this.fetchData() // 更新每页显示的条目数量后重新请求数据
      },
      handleCurrentChange (newPage) {
        this.currentPage = newPage
        this.fetchData() // 更新当前页数后重新请求数据
      },
      handleNewSizeChange (newSize) {
        this.pageNewSize = newSize
        this.searchpage() // 更新每页显示的条目数量后重新请求数据
      },
      handleNewCurrentChange (newPage) {
        this.currentNewPage = newPage
        this.searchpage() // 更新当前页数后重新请求数据
      },
    },
    mounted() {
        this.restaurants = this.loadAll();
      },
    async created(){
        let user = JSON.parse(localStorage.getItem("honey-user") || '{}')
        const config = {
            headers: {
                // 设置内容类型为JSON
                'Content-Type': 'application/json;charset=UTF-8',
                // 添加token到请求头
                'token': user.token || '',
            }
        }
        //this.$request.get('/device').then(res => {
      const res = await axios.get('http://127.0.0.1:8000/device',config);
    this.tableData = res.data.data
        const Name = this.$route.query.name
        this.tableData = this.tableData.filter(item => item.address == Name)
    for (var i = 0; i < this.tableData.length; i++) {
                  if (this.tableData[i].state == 0)
                      this.tableData[i].state = '离线'
                  else
                      this.tableData[i].state = '在线'
              }
    this.fetchData()
        if(res.data.code == '401')
            this.$router.push('/')
    //})
    }
  }
  </script>
  
  <style>
    #search{
      width: 600px;
      position: fixed;
      left: auto;
      top: 80px;
    }
    #table{
      line-height: 50px;
    }
    #searchicon{
      position: fixed;
      left: 1300px;
      top: 80px;
    }
  </style>